package com.zj.leetcode.medium.tree;

/**
 * @program: algorithm
 * @description: 最长同值路径
 * 687 longest-univalue-path
 * @author: Zhang Bo
 * @create: 2022-06-07 10:18:33
 **/
public class LongestUnivaluePath {
    public static void main(String[] args) {
        Solution solution = new LongestUnivaluePath().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {


        /**
         * [5,4,5,1,1,5]
         * 5
         * 4       5
         * 1     1       5
         * <p>
         * [1,2,2,2,2,2,2,2]
         * 1
         * 2     2
         * 2 2   2 2
         * 2
         *
         * @param root
         * @return
         */
        int max = 0;

        public int longestUnivaluePath(TreeNode root) {
            this.dfs(root);
            return max;
        }

        public int dfs(TreeNode node) {
//            if (node == null) {
//                return 0;
//            }
//            int left = this.dfs(node.left);
//            int right = this.dfs(node.right);
//
//            if (node.left != null && node.left.val == node.val) {
//                left++;
//            }
//            if (node.right != null && node.right.val == node.val) {
//                right++;
//            }
//            max = Math.max(max, left + right);
//            return Math.max(left, right);

            if (node == null) {
                return 0;
            }
            int left = dfs(node.left);
            int right = dfs(node.right);
            int lRet = 0, rRet = 0;
            if (node.left != null && node.left.val == node.val) {
                lRet = left + 1;
            }

            if (node.right != null && node.right.val == node.val) {
                rRet = right + 1;
            }

            max = Math.max(max, lRet + rRet);
            return Math.max(lRet, rRet);

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
